import pymysql

class MyORM:
    def __init__(self):
        # 建立与数据库的连接
        conn = pymysql.connect(
            host="192.168.1.129",
            port=3306,
            user="admin1",
            password="123",
            database="mumushouji",
            charset="utf8",
            cursorclass=pymysql.cursors.DictCursor,
            autocommit=True
        )
        # 实例化一个游标对象
        cursor = conn.cursor()
        self.cursor = cursor

    def execute(self,sql):
        self.cursor.execute(sql)
        return self.cursor.fetchall()

class User:
    table_name = "user"
    def __init__(self,**kwargs):
        for k,v in kwargs.items():
            self.__setattr__(k,v)
        # print(self.__dict__)

    def query_one(self,select_params=None,**where_params):

        if select_params is not None and type(select_params) is list:
            # 进行sql语句的拼接
            sql = "select "
            for i in select_params:
                sql += i+","
            sql = sql[0:-1]
            sql = sql + " from " + self.table_name
            print(sql)
        else:
            sql = "select * from " + self.table_name

        # select username,nickname from user where user_id=3 and username='3@qq.com'
        print(where_params)
        if where_params is not None:
            sql = sql + " where "
            for k,v in where_params.items():
                sql += " %s='%s' and" % (k,v)
            sql += ' 1=1 limit 1'
            print(sql)
        # return 0
        return MyORM().execute(sql)

    def insert(self):
        # sql = "insert into user(username,password,nickname,picture,job) values (%s)"
        print(self.__dict__)
        keys = []
        values = []
        for k,v in self.__dict__.items():
            keys.append(k)
            values.append(v)
        sql = "insert into %s(%s) values('%s')" % (self.table_name,','.join(keys), "','".join(values))
        print(sql)
        return MyORM().execute(sql)


if __name__ == "__main__":
    user = User(username="dazhoulaoshi",
                password="123",
                nickname="大周老师",
                picture="1.jpg",
                job="全栈工程师")
    user.insert()
